package com.yuxi.al.leercode;

/**
 * 两个数字之间的汉明距离就是其二进制数对应位不同的个数
 * Created by yuxi on 2017/3/31.
 */
public class HammingDistance {
    public static void main(String[] args) {
        int a = 223, b = 16;
        int distance = hammingDistance(a, b);
        System.out.println(distance);

        System.out.println(hammingDistance2(a, b));
    }

    public static int hammingDistance2(int x, int y) {
        int xor = x ^ y;
        int res = 0;
        while (xor != 0) {
            res += xor & 1;
            xor >>= 1;
        }
        return res;
    }

    private static int hammingDistance(int a, int b) {
        //相^之后二进制表示  相同为0 相异为1
        int tmp = a ^ b;
        //统计个数
        int count = 0;
        while (tmp != 0) {
            //求1的个数
            if ((tmp & 1) == 1) {
                count++;
            }
            tmp >>=1;

        }
        return count;
    }

}
